﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forum.Web.BaseCode;
using System.IO;
using Forum.BLL.Post;
using Forum.Entity.Post;

namespace Forum.Web.Controllers
{
    public class FileController : BaseController
    {
        
        public ActionResult Upload()
        {
            //返回内容必需是标准的json字符串，结构可以是如下：{"err":"","msg":"200906030521128703.gif"} 或者 {"err":"","msg":{"url":"200906030521128703.jpg","localfile":"test.jpg","id":"1"}} 注：若选择结构2，则url变量是必有
            Response.Charset = "UTF-8";

            // 初始化一大堆变量
            string inputname = "filedata";//表单文件域name
            
            byte[] buffer; // 统一转换为byte数组处理
            string fileName = "";
            string error = "";
            object msg = null;
           
            HttpFileCollectionBase filecollection = Request.Files;
            HttpPostedFileBase postedfile = filecollection.Get(inputname);

            if (base.MemberInfo.IsLogin == false)
            {
                error = "用户没有登录";
            }
            else if (postedfile.ContentLength == 0)
            {
                error = "无数据提交";
            }
            else
            {
                // 读取原始文件名
                fileName = postedfile.FileName;
                // 初始化byte长度.
                buffer = new Byte[postedfile.ContentLength];

                // 转换为byte类型
                System.IO.Stream stream = postedfile.InputStream;
                stream.Read(buffer, 0, postedfile.ContentLength);
                stream.Close();

                if (buffer.Length > Paras.AttachMaxSize)
                {
                    error = "文件大小超过" + Paras.AttachMaxSize + "字节";
                }
                else
                {
                    // 取上载文件后缀名
                    string extension = Path.GetExtension(fileName).Trim('.');

                    if (!Paras.AttachExt.Contains(extension))
                    {
                        error = "上传文件扩展名必需为：" + Paras.AttachExt;
                    }
                    else
                    {
                        string attachSubDir = null;

                        if (Paras.AttachSaveMode == "2")
                        {
                            attachSubDir = "month_" + DateTime.Now.ToString("yyMM");
                        }
                        else
                        {
                            attachSubDir = "day_" + DateTime.Now.ToString("yyMMdd");
                        }

                        string attachFullDir = Paras.AttachDir + "/" + attachSubDir + "/";

                        // 生成随机文件名
                        Random random = new Random(DateTime.Now.Millisecond);
                        string discFilename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

                        string target = attachFullDir + discFilename;

                        try
                        {
                            if (Directory.Exists(attachFullDir))
                            {
                                Directory.CreateDirectory(attachFullDir);
                            }

                            using (FileStream fs = new FileStream(Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write))
                            {
                                fs.Write(buffer, 0, buffer.Length);
                                fs.Flush();
                                fs.Close();
                            }

                            UploadBO upload = new UploadBO();
                            UploadInfo info = new UploadInfo();
                            info.Extension = extension;
                            info.InputTime = DateTime.Now;
                            info.MemberID = base.MemberInfo.MemberID;
                            info.MemberName = base.MemberInfo.MemberLoginName;
                            info.Name = fileName;
                            info.Path = target;
                            info.Size = buffer.Length;
                            upload.Save(info);

                            msg = new { url = target, id = info.ID };
                        }
                        catch (Exception ex)
                        {
                            error = ex.Message.ToString();
                        }

                       
                       // msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
                    }
                }
            }

            var obj = new { err = error, msg = msg };
            return this.Json(obj);
        }
        
       
    }
}
